<?php
namespace App\Http\Controllers\SysAdmin;

use App\Models\Company;
use App\Models\CorpInfo;
use App\Models\Group;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\SysAdmin\BaseController;
use App\Models\Keys;
use Curl\Curl;
use App\Models\RoleUser;
use App\Models\Roles;
use Illuminate\Support\Facades\Log;

//系统权限管理，仅系统管理员使用
class PermissionController extends BaseController
{
    protected $role;


    public function __construct() {
        parent::__construct();
        $this->role = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->whereIn('role_id',['9'])->get();
        if(count($this->role) == 0){
            abort(403,'您没有权限访问该页面');
        }
    }


    //通讯录首页
    public function getIndex(Request $request)
    {
        $key_name = $request->input('name','');

        $tongxunlu = array();
        $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
        $groups = $groups->toArray();
        $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
        array_unshift($groups,$groups_add);
        if(empty($key_name)){
            $users = User::where('corpid',$this->corpid)->where('status','1')->select('id','qw_userid','user_logo','qw_name','group_id','is_leader','is_sales')->orderBy('is_leader','desc')->orderByRaw('CONVERT (kh_users.qw_name USING gbk)')->get();
        }else{
            $users = User::where('corpid',$this->corpid)->where('qw_name','like','%'.$key_name.'%')->where('status','1')->select('id','qw_userid','user_logo','qw_name','group_id','is_leader','is_sales')->orderBy('is_leader','desc')->orderByRaw('CONVERT (kh_users.qw_name USING gbk)')->get();
        }
        //$users = User::where('corpid',$this->corpid)->where('status','1')->select('id','qw_userid','user_logo','qw_name','group_id','is_leader')->get();
        foreach ($users as $u){
            $u->role = RoleUser::where('corpid',$this->corpid)->where('user_id',$u->id)->lists('role_id');
        }
        $users = $users->toArray();
        foreach ($groups as &$g){
            $g['member'] = $this->filterUser($g['id'],$users);
            if($g['fid'] == 0){
                $tongxunlu[] = $g;
            }
        }
        foreach ($tongxunlu as $k=>&$t){
            if($t['id'] !=0){
                $t['child'] = $this->filterGroup($t['id'],$groups);
                foreach ($t['child'] as &$cld){
                    $cld['child'] = $this->filterGroup($cld['id'],$groups);
                }
            }
        }
        $rolearray = array('9'=>'总','10'=>'考','11'=>'业','12'=>'奖');
        
        
        if(is_mobile()){
            $view = 'sysadmin.permission.main-list';
        }else{
            $view = 'pc_sysadmin.permission.main-list';
        }

        $active = $request->input('active',0);
        
        
        return view($view)
            ->with('tongxunlu',$tongxunlu)
            ->with('rolearray',$rolearray)
            ->with('active',$active);
    }

    private function filterUser($group_id,$users){
        $return = array();
        foreach ($users as $u){
            if($u['group_id'] == $group_id){
                $return[] = $u;
            }
        }
        //dd($return);
        return $return;
    }

    //筛选用户

    private function filterGroup($group_id,$groups){
        $return = array();
        foreach ($groups as $u){
            if($u['fid'] == $group_id){
                $return[] = $u;
            }
        }
        return $return;
    }

    //筛选组

    public function getRoleIndex(Request $request)
    {
        $roles = Roles::all();
        //$users = User::where('corpid',$this->corpid)->get();
        $view = 'sysadmin.permission.authority-manage';
        return view($view)
            ->with('roles',$roles);
    }


    //所有角色列表首页

    public function getShowAdmins(Request $request)
    {
        $role_id = $request->input('roleid',0);
        if($role_id <=0){
            return 'roleid错误';
        }
        $role = Roles::find($role_id);
        $admins = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->get();
        if($role_id == 9){
            $view = 'sysadmin.permission.sysadmin-info';
        }else{
            $view = 'sysadmin.permission.perform-manage';
        }
        return view($view)
            ->with('role',$role)
            ->with('admins',$admins);
    }


    //各个系统角色对应的管理员列表

    public function getAddAdmin(Request $request)
    {
        $role_id = $request->input('roleid',0);
        if($role_id <=0){
            return 'roleid错误';
        }
        //获取多级通讯录
        $tongxunlu = $this->getTongxunlu();
        $admins = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->lists('user_id');
        $admins = $admins->toArray();
        $rolearray = array('9'=>'总','10'=>'考','11'=>'业','12'=>'奖');
        
        if($role_id == 9){
            $view = 'sysadmin.permission.trans-sysadmin';
        }else{
            $view = 'sysadmin.permission.add-manage';
        }
        return view($view)
            ->with('roleid',$role_id)
            ->with('admins',$admins)
            ->with('tongxunlu',$tongxunlu)
            ->with('rolearray',$rolearray);
    }

    //增加管理员,显示通讯录

    public function getTongxunlu()
    {
        $tongxunlu = array();
        $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
        $groups = $groups->toArray();
        $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
        array_unshift($groups,$groups_add);
        $users = User::where('corpid',$this->corpid)->where('status','1')->orderBy('is_leader','desc')->orderByRaw('CONVERT (kh_users.qw_name USING gbk)')->select('id','qw_userid','user_logo','qw_name','group_id','is_leader')->get();
        foreach ($users as $u){
            $u->role = RoleUser::where('corpid',$this->corpid)->where('user_id',$u->id)->lists('role_id');
        }
        $users = $users->toArray();
        foreach ($groups as &$g){
            $g['member'] = $this->filterUser($g['id'],$users);
            if($g['fid'] == 0){
                $tongxunlu[] = $g;
            }
        }
        foreach ($tongxunlu as $k=>&$t){
            if($t['id'] !=0){
                $t['child'] = $this->filterGroup($t['id'],$groups);
                foreach ($t['child'] as &$cld){
                    $cld['child'] = $this->filterGroup($cld['id'],$groups);
                }
            }
        }
        return $tongxunlu;
    }


    //删除管理员，显示通讯录

    public function getDelAdmin(Request $request)
    {
        $role_id = $request->input('roleid',0);
        if($role_id <=0 ){
            return '传递参数错误';
        }

        $roleuser = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->lists('user_id');
        if(empty($roleuser)){
            return '记录不存在';
        }

        $view = 'sysadmin.permission.delete-manage';
        return view($view)
            ->with('roleid',$role_id)
            ->with('scope',$roleuser);

    }

    //新增管理员
    public function postAddAdmin(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $role_id = $request->input('roleid',0);
        if($role_id <=0){
            return 'roleid错误';
        }
        $user_ids = $request->input('userid',0);
        $user_ids = json_decode($user_ids);
        foreach ($user_ids as $u){
            $admin = RoleUser::where('corpid',$this->corpid)->where('role_id','9')->where('user_id',$u)->first();
            if(!empty($admin) && $role_id != 9){
                $result['status'] = 'fail';
                $result['msg'] = getUserName($u).'为系统管理员,不需再分配权限';
                return Response::json($result);
            }
            $exist = RoleUser::where('corpid',$this->corpid)->where('role_id',$role_id)->where('user_id',$u)->first();
            if(empty($exist)){
                $newrole = new RoleUser();
                $newrole->user_id = $u;
                $newrole->role_id = $role_id;
                $newrole->corpid = $this->corpid;
                $newrole->save();
            }
            if($role_id == 9){
                $other = RoleUser::where('corpid',$this->corpid)->where('user_id',$u)->whereIn('role_id',['10','11','12'])->delete();
                $otheradmin = RoleUser::where('corpid',$this->corpid)->where('user_id','!=',$u)->where('role_id','9')->delete();
            }
        }


        return Response::json($result);
    }

    //删除管理员
    public function postDelAdmin(Request $request)
    {
        $role_id = $request->input('roleid',0);
        if($role_id <=0){
            return 'roleid错误';
        }
        $user_id = $request->input('userid',0);
        $user_id = json_decode($user_id);
        $roleuser = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->whereIn('user_id',$user_id)->delete();
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );

        return Response::json($result);
    }

    //同时显示管理员和被管理人页面
    public function getAdminScopelist(Request $request){
        $role_id = $request->input('roleid',0);
        $user_admin = $request->input('adminid',0);
        if($role_id <=0 || $user_admin<=0 ){
            return '传递参数错误';
        }

        $roleuser = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->where('user_id',$user_admin)->first();
        if(empty($roleuser)){
            return '记录不存在';
        }
        if($roleuser->role_id == 9){
            $scope = array();
        }else{
            $scope = !empty($roleuser->scope)?unserialize($roleuser->scope):array();
            foreach ($scope as $k=>&$s){
                $su  = User::where('status','1')->find($s);
                if(empty($su)){
                    unset($scope[$k]);
                }

            }
            $scope_users = User::where('status', '1')->whereIn('id',$scope)->orderByRaw('CONVERT (kh_users.qw_name USING gbk)')->lists('id')->toArray();
            $scope = $scope_users;
        }
        $role = Roles::find($role_id);
        //用户拥有的所有管理员角色
        //$allrole = RoleUser::where('corpid',$this->corpid)->where('user_id',$user_admin)->get();
        $rolearray = array('9'=>'总','10'=>'考','11'=>'业','12'=>'奖');
        $view = 'sysadmin.permission.managed-person';
        return view($view)
            ->with('adminid',$user_admin)
            ->with('roleid',$role_id)
            ->with('role',$role)
            ->with('rolearray',$rolearray)
            ->with('scope',$scope);
    }


    //增加被管理人,显示通讯录
    public function getAddScope(Request $request)
    {
        $role_id = $request->input('roleid',0);
        $adminid = $request->input('adminid',0);
        if($role_id <=0 || $adminid <=0){
            return '参数错误';
        }
        //获取多级通讯录
        $tongxunlu = $this->getTongxunlu();
        $adminscope = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->where('user_id',$adminid)->first();
        if($adminscope->role_id == 9){
            $scope = array();
        }else{
            $scope = !empty($adminscope->scope)?unserialize($adminscope->scope):array();
        }
        $view = 'sysadmin.permission.add-scope';
        return view($view)
            ->with('roleid',$role_id)
            ->with('scope',$scope)
            ->with('tongxunlu',$tongxunlu)
            ->with('adminid',$adminid);
    }


    //删除被管理人，显示通讯录
    public function getDelScope(Request $request)
    {
        $role_id = $request->input('roleid',0);
        $adminid = $request->input('adminid',0);
        if($role_id <=0 || $adminid <=0){
            return '参数错误';
        }

        $adminscope = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->where('user_id',$adminid)->first();
        if(empty($adminscope)){
            return '记录不存在';
        }
        if($adminscope->role_id == 9){
            $scope = array();
        }else{
            $scope = !empty($adminscope->scope)?unserialize($adminscope->scope):array();
        }

        $view = 'sysadmin.permission.delete-scope';
        return view($view)
            ->with('roleid',$role_id)
            ->with('scope',$scope)
            ->with('adminid',$adminid);

    }

   /* //显示管理员管辖范围
    public function getAdminScope(Request $request)
    {
        $role_id = $request->input('roleid',0);
        $user_admin = $request->input('adminid',0);
        if($role_id <=0 || $user_admin<=0 ){
            return '传递参数错误';
        }

        $roleuser = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->where('user_id',$user_admin)->first();
        if(empty($roleuser)){
            return '记录不存在';
        }
        if($roleuser->role_id == 9){
            $scope = '';
        }else{
            $scope = unserialize($roleuser->scope);
        }
        $view = 'sysadmin.permission.delete-scope';
        return view($view)
            ->with('adminid',$user_admin)
            ->with('roleid',$role_id)
            ->with('scope',$scope);

    }*/

    //设置管理员管辖范围
    public function postSetScope(Request $request)
    {
        $role_id = $request->input('roleid',0);
        $user_admin = $request->input('adminid',0);
        $user_ids = $request->input('userid',0);
        $user_ids = json_decode($user_ids);
        if($role_id <=0 || $user_admin<=0 || count($user_ids)==0){
            return '传递参数错误';
        }

        $roleuser = RoleUser::where('role_id',$role_id)->where('corpid',$this->corpid)->where('user_id',$user_admin)->first();
        $roleuser->scope = serialize($user_ids);
        $roleuser->save();
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        return Response::json($result);
    }


}


